package org.lex.keytool.util.process;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;

import org.lex.keytool.util.ThreadPool;

public class ProcessLauncuer {
	public Future<Integer> launch(Writer out, Writer err, String[] commands) throws IOException {
		return launch(out, err, Arrays.asList(commands));
	}

	public Future<Integer> launch(Writer out, Writer err, List<String> commands) throws IOException {
		ProcessBuilder pb = new ProcessBuilder(commands);
		Process proc = pb.start();
		ExecutorService exec = ThreadPool.getInstance().getExecutor();
		exec.execute(new Copier(proc.getInputStream(), out));
		exec.execute(new Copier(proc.getErrorStream(), err));
		return exec.submit(new ProcessWaiter(proc));
	}

	private static class Copier implements Runnable {
		private final Reader in;
		private final Writer out;

		public Copier(InputStream in, Writer out) {
			this.in = new InputStreamReader(in);
			this.out = out;
		}

		public void run() {
			int ch = -1;
			try {
				while (-1 != (ch = in.read())) {
					out.write(ch);
					out.flush();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
